import React, {Component} from 'react'


import {
    DeviceEventEmitter,
    Image,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import PerformancePage from "./PerformancePage";
import IparNetwork, {getSynPaysSellerAuth, SERVER_TYPE, SynpaysTeken} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import WalletPage from "../walletAndWitdraw/WalletPage";
import BusinessPlanPage from "./BusinessPlanPage";
import SubAccountsPage from "./SubAccountsPage";


export default class MyGeneralBusinessPage extends Component {

    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.country = '';
        this.planNamesData = [
            {color: 'black', value: 1, rank: 2},
            {color: '#333333', value: 1, rank: 3},
            {color: '#4d4d4d', value: 1, rank: 4},
            {color: '#6a6a6a', value: 0, rank: 5},
            {color: '#7d7d7d', value: 0, rank: 6},
            {color: '#a8a8a8', value: 1, rank: 7},
            {color: '#b2b2b2', value: 0, rank: 8},
            {color: '#dddddd', value: 0, rank: 9},
        ];


        this.state = {
            isLoading: false,
            plansData: this.props.plansData,
            planPerformanceColors: [],
            planPerformanceValues: [],
            planPerformanceValue: 0,
            balance: 0.00,//余额
            currency: '',

            chartsData: [],


            mainUserNewChildren: [],//新增成员
            mainUserNotActivChildren: [],//新增成员
        }

    }

    componentWillUnmount() {
        this.iparNetwork = null;
        this.country = null;
        this.planNamesData = null;
    }

    componentDidMount() {
        CommonUtils.getAcyncInfo('country_iso')
            .then((country) => {
                this.country = country;
                // this.onLoadPlansDdata();

                this.getBalanceInfo();
                this.getData();

            });


    }


    componentWillReceiveProps(nexProps) {

        if (this.props.plansData !== nexProps.plansData ||
            this.props.rewardStatisticsData !== nexProps.rewardStatisticsData) {

            let data = nexProps.plansData;

            let _planPerformanceValue = 0;
            let _planPerformanceColors = [];
            let _planPerformanceValues = [];
            for (let i = 0, len = data.length; i < len; i++) {
                let namesDatum = this.planNamesData[data[i].rank - 2];
                _planPerformanceColors.push(namesDatum.color);

                if (nexProps.rewardStatisticsData) {
                    let _message = nexProps.rewardStatisticsData.rank[namesDatum.rank];

                    let message = (_message && _message.pv) || '';

                    _planPerformanceValues.push(message);
                    _planPerformanceValue += message;
                    namesDatum.value = message;
                }

            }

            this.setState({
                plansData: data,
                planPerformanceValue: _planPerformanceValue,
                planPerformanceColors: _planPerformanceColors,
                planPerformanceValues: _planPerformanceValues,
            })
        }
    }

    /*获取Synpays金额*/
    getBalanceInfo() {
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'Wallet?', 'UserID=' + this.props.userId, SynpaysTeken)
            .then((result) => {
                let data = result.data.Balance;
                if (data) {
                    this.setState({
                        balance: data.Balance,
                        currency: data.Currency,
                    })
                }
            })
            .catch((error) => {
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })
    }


    /**
     * 获取想要的数据
     */
    getData() {

        this.getChildren(0);//获取新增成员
        this.getChildren(1);//获取未活跃成员

        this.getCharts();//获取订单统计
    }


    /**
     * 获取订单统计
     */
    getCharts() {
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getUserRewardInfo?',
            'main_user_id=' + this.props.userId + '&country=' + this.country)
            .then((result) => {
                if (result.code === 200) {
                    this.setState({
                        chartsData: result.data,
                    })
                }
            })
            .catch((error) => {
                console.log('MyGeneralBusinessPage-----getCharts--error: ', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })


    }


    /**
     * 获取新增成员
     * @param  type === 0 新增成员
     */
    getChildren(type) {
        let _param = type === 1 ? '&is_ibm=0' : '';
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getTeam?', 'user_id=' + this.props.userId + _param)
            .then((result) => {
                if (result.code === 200) {
                    let state = this.state;
                    this.setState({
                        mainUserNewChildren: type === 0 ? result.data : state.mainUserNewChildren,
                        mainUserNotActivChildren: type !== 0 ? result.data : state.mainUserNotActivChildren,
                    })
                }
            })
            .catch((error) => {

                console.log('MyGeneralBusinessPage----getMainUserNewChildren---error', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })

    }


    renderPlanLable(rowData, index) {


        let planNamesDatum = this.planNamesData[rowData.rank - 2];

        let props = this.props;

        let color = planNamesDatum.color;
        let value = planNamesDatum.value;

        return (<TouchableOpacity
            key={index}
            onPress={() => props.gotoPage(index + 1)}
            style={[StyleUtils.justifySpace, {marginBottom: 22}]}>
            <View style={{width: 22, height: 22, backgroundColor: color}}/>
            <Text style={[styles.planLable, StyleUtils.smallFont]}>{rowData.name}</Text>
            <Text style={{fontSize: 16, color: 'black'}}>{(value || 0).toFixed(2)}</Text>
        </TouchableOpacity>)
    }


    /**
     * 点击
     * */
    onClick(type, params) {

        let _component = null;
        let _params = {...this.props};
        // if (type === 'WalletPage') {
        //
        // }//

        switch (type) {
            case 'WalletPage':
                _component = WalletPage;
                break;
            case 'B_plan':
                _component = BusinessPlanPage;
                break;
            case 'users':
                _component = SubAccountsPage;
                _params = {
                    ...this.props,
                    type: 'checkDetails',
                    users: this.props.usersData,
                    callBack: (index) => {
                        this.props.gotoPage(index)
                    }
                };
                break;
            case 'mainUserNotActivChildren':
            case 'mainUserNewChildren':
                _component = SubAccountsPage;
                _params = {
                    ...this.props, type: 'newAssociates',
                    users: type === 'mainUserNotActivChildren' ? this.state.mainUserNotActivChildren : this.state.mainUserNewChildren,
                    title: params
                };
                break;
        }

        if (_component) {
            this.props.navigator.push({
                component: _component,
                name: _component + "",
                params: _params,
            })
        }

    }

    render() {

        let state = this.state;
        return <View style={StyleUtils.flex}>

            <Navigation onClickLeftBtn={() => this.props.navigator.popToTop()}/>

            <ScrollView
                refreshControl={
                    <RefreshControl
                        refreshing={state.isLoading}
                        onRefresh={() => this.getData()}
                    />
                }
            >
                <View style={{padding: 20}}>
                    {/**top view*/}
                    <View style={styles.topView}>
                        <Text
                            style={[styles.normalText, StyleUtils.smallFont]}>{I18n.t('default.availableBalance')}</Text>
                        <Text
                            numberOfLines={1}
                            style={[styles.boldText, StyleUtils.smallFont]}>{state.balance} {state.currency}</Text>
                        {ViewUtils.getButton(I18n.t('b.checkDetails'), () => this.onClick('WalletPage'), styles.topBtnStyle, {color: 'black'})}
                    </View>


                    <Text style={[{
                        fontSize: 18,
                        color: 'black',
                        marginTop: 20,
                        textAlign: 'left'
                    }, StyleUtils.smallFont]}>{I18n.t('b.estimatedPV')}</Text>


                    <PerformancePage
                        performanceValues={state.planPerformanceValues}
                        performanceColors={state.planPerformanceColors}
                        value={state.planPerformanceValue}
                        type={0}
                    />


                    {state.plansData ? state.plansData.map((item, i) => {
                        return this.renderPlanLable(item, i);
                    }) : null}

                    {/*{ViewUtils.getButton(I18n.t('b.checkDetails'), () => this.onClick('B_plan'), styles.topBtnStyle, {color: 'black'})}*/}
                    {/*<View*/}
                    {/*style={[StyleUtils.justifySpace, styles.reentryViewStyle, {marginTop: 32, borderTopWidth: 1,}]}>*/}

                    {/*<Text>{I18n.t('b.reentryNotifications')}</Text>*/}

                    {/*<View*/}
                    {/*style={[StyleUtils.center, {*/}
                    {/*borderRadius: 10,*/}
                    {/*width: 20,*/}
                    {/*height: 20,*/}
                    {/*backgroundColor: 'black'*/}
                    {/*}]}>*/}
                    {/*<Text numberOfLines={1} style={styles.circularText}>0</Text>*/}
                    {/*</View>*/}
                    {/*</View>*/}


                    {/**新增成员*/}
                    <TouchableOpacity
                        onPress={() => this.onClick('mainUserNewChildren', I18n.t('b.newAssociates'))}
                        style={[StyleUtils.justifySpace, styles.reentryViewStyle]}>

                        <Text style={StyleUtils.smallFont}>{I18n.t('b.newAssociates')}</Text>

                        <View
                            style={[StyleUtils.center, {
                                borderRadius: 10,
                                width: 20,
                                height: 20,
                                backgroundColor: 'black'
                            }]}>
                            <Text numberOfLines={1}
                                  style={[styles.circularText, StyleUtils.smallFont]}>{state.mainUserNewChildren.length}</Text>
                        </View>
                    </TouchableOpacity>

                    {/**未活跃成员*/}
                    <TouchableOpacity
                        onPress={() => this.onClick('mainUserNotActivChildren', I18n.t('b.associatesNeedService'))}
                        style={[StyleUtils.justifySpace, styles.reentryViewStyle,]}>

                        <Text style={StyleUtils.smallFont}>{I18n.t('b.associatesNeedService')}</Text>

                        <View
                            style={[StyleUtils.center, {
                                borderRadius: 10,
                                width: 20,
                                height: 20,
                                backgroundColor: 'black'
                            }]}>
                            <Text
                                style={[styles.circularText, StyleUtils.smallFont]}>{state.mainUserNotActivChildren.length}</Text>
                        </View>
                    </TouchableOpacity>


                    <View style={{alignItems: 'center', paddingTop: 24}}>
                        <Text
                            style={[{textAlign: 'center'}, StyleUtils.smallFont]}>{I18n.t('b.ActivatedBusiness')}</Text>

                        <View style={[StyleUtils.justifySpace, {marginTop: 26, marginBottom: 26}]}>
                            <Image
                                style={{width: 48, height: 48}}
                                source={require('../../../res/images/ic_shop.png')}/>
                            <Text style={[{
                                fontSize: 38,
                                alignItems: 'center'
                            }, StyleUtils.smallFont]}>+ {(this.props.usersData && this.props.usersData.length) || 0}</Text>

                        </View>
                    </View>


                    {ViewUtils.getButton(I18n.t('b.checkDetails'), () => this.onClick('users'), [styles.topBtnStyle, {marginBottom: 28}], {color: 'black'})}

                    <Text style={[StyleUtils.title, {textAlign: 'left'},]}>{I18n.t('b.myPerformance')}</Text>

                    <PerformancePage
                        dataSource={state.chartsData || []}
                        type={1}
                    />

                </View>

            </ScrollView>


        </View>
    }


}

const styles = StyleSheet.create({

    topView: {
        backgroundColor: 'black',
        height: 200,
        width: '100%',
        alignItems: 'center',
        padding: 20,
    },

    normalText: {
        color: '#f3f3f3',
        fontSize: 16,
        marginTop: 16,
        marginBottom: 16,
    },

    boldText: {
        color: 'white',
        fontSize: 34,
        flex: 1
    },

    topBtnStyle: {
        backgroundColor: 'white',
        borderWidth: 1,
        borderColor: '#b7b7b7',
        height: 42,
    },

    planLable: {
        borderColor: 'black',
        flex: 1,
        paddingLeft: 8,
    },
    reentryViewStyle: {
        borderBottomWidth: 1,
        borderColor: '#e7e7e7',
        paddingTop: 16,
        paddingBottom: 16,

    },

    circularText: {
        color: 'white',
        textAlign: 'center',
        backgroundColor: 'transparent',
    },


});
